package com.testingedu.action.front;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;

import com.testingedu.action.background.RequestContext;
import com.testingedu.jdbcDao.TResourceDao;
import com.testingedu.model.TResource;

public class TResourceAction extends RequestContext {

	private static final long serialVersionUID = 7932071761324806829L;
	private TResource tResource;

	public TResource gettResource() {
		return tResource;
	}

	public void settResource(TResource tResource) {
		this.tResource = tResource;
	}

	private static TResourceDao tResourceDao = new TResourceDao();

	public void list_() throws Exception {
		createQueryResult();
		tResourceDao.list(queryResult, null);
		request.setAttribute("queryResult", queryResult);
		request.getRequestDispatcher("/resource/list.jsp").forward(request,
				response);
	}

	public void info_() throws Exception {
		tResource = tResourceDao.info(tResource.getId());
		request.setAttribute("tResource", tResource);
		request.getRequestDispatcher("/resource/info.jsp").forward(request,
				response);
	}

	public void download_() throws Exception {
		tResource = tResourceDao.info(tResource.getId());
		// 处理请求
		// 读取要下载的文件
		File f = null;
		if ("n".equals(tResource.getIsLocal())) {
			response.getWriter().write(
					"{\"uri\":\"" + tResource.getPath() + "\"}");
			response.getWriter().close();
		} else {
			if ("y".equals(tResource.getIsLocal())) {
				f = new File(servletContext.getRealPath(File.separator)
						+ tResource.getPath());
				if (f.exists()) {
					FileInputStream fis = new FileInputStream(f);
					String filename = URLEncoder.encode(f.getName(), "utf-8"); // 解决中文文件名下载后乱码的问题
					byte[] b = new byte[fis.available()];
					fis.read(b);
					response.setCharacterEncoding("utf-8");
					response.setHeader("Content-Disposition",
							"attachment; filename=" + filename + "");
					// 获取响应报文输出流对象
					ServletOutputStream out = response.getOutputStream();
					// 输出
					out.write(b);
					out.flush();
					out.close();
				}
			}
		}
	}
}
